﻿#include "saveimgworker.h"
#include <QDir>
#include <QDebug>
#include <QImage>
#include <QDateTime>
#include <QCoreApplication>
SaveImgWorker::SaveImgWorker(QObject *parent) : QObject(parent)
{
    m_nIndex = 1;
    m_nIndexM = 1;
}



SaveImgWorker::~SaveImgWorker()
{

}
void SaveImgWorker::Initialize()
{

}

void SaveImgWorker::handleFrame(CFrameInfo frameInfo)
{
    if(m_cSave.m_nSource){
        saveFrameAsJPEG(frameInfo);
    }
}

void SaveImgWorker::woodFrame(CFrameInfo frameInfo)
{
    if(m_cSave.m_nSource){
        saveFrameAsJPEG(frameInfo);
    }
}

void SaveImgWorker::setRoi(const QRect &roi)
{
    m_roi = roi;
}

void SaveImgWorker::saveFrameAsJPEG(const CFrameInfo& frameInfo)
{
    QImage::Format format = QImage::Format_Invalid;
    if (frameInfo.m_ePixelType == gvspPixelMono8) {
        format = QImage::Format_Grayscale8;
    } else if (frameInfo.m_ePixelType == gvspPixelRGB8) {
        format = QImage::Format_RGB888;
    }
    if (format == QImage::Format_Invalid) {
        qWarning() << "Unsupported pixel format:" << frameInfo.m_ePixelType;
        return;
    }

    QImage image(
        frameInfo.m_pImageBuf.get(),
        frameInfo.m_nWidth,
        frameInfo.m_nHeight,
        format
        );

    if (image.isNull()) {
        qWarning() << "Failed to create QImage.";
        return;
    }
    // 如果有设置ROI，则裁剪图像
    if (m_roi.isValid() && !m_roi.isEmpty()) {
        // 确保ROI在图像范围内
        QRect validRoi = m_roi.intersected(image.rect());
        if (!validRoi.isEmpty()) {
            image = image.copy(validRoi);
        }
    }

    // 构建保存路径
    QString appDir = QCoreApplication::applicationDirPath();
    QString savePath =  QString("%1/Pic/ccd%2/Source Image/").arg(appDir).arg(getCameraID(frameInfo.cameraKey));

    // 生成唯一的文件名，例如：Camera1_20231010_123456.jpg
    QString fileName = QString("Pic%1_%2_%3.jpg")
                           .arg(getCameraID(frameInfo.cameraKey)).arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")).arg(m_nIndex);
    QString filePath = savePath + fileName;

    // 保存为JPEG格式
    if (image.save(filePath, "JPEG")) {
        m_nIndex++;
    } else {
        qWarning() << "Failed to save image.";
    }
}

int SaveImgWorker::getCameraID(QString cameraKey)
{
    if (cameraKey == "Machine Vision:EC48318AAK00038") {
        return 1;
    }

    if (cameraKey == "Huaray Technology:EB29285AAK00008") {
        return 2;
    }

    if (cameraKey == "Huaray Technology:BK27071AAK00002") {
        return 3;
    }

    if (cameraKey == "Huaray Technology:DA56668AAK00003") {
        return 4;
    }

    if (cameraKey == "Machine Vision:DL00908CAK00014") {
        return 5;
    }

    if (cameraKey == "Machine Vision:DL00908CAK00005") {
        return 6;
    }
    return 0;
}
